from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from app.services.auth_service import AuthService
from app.utils.minio_util import MinioUtil

bp = Blueprint('profile', __name__)
auth_service = AuthService()
minio_util = MinioUtil()

@bp.route('/profile')
@login_required
def profile():
    return render_template('components/profile.html')

@bp.route('/api/profile/info')
@login_required
def get_profile_info():
    return {
        'success': True,
        'data': {
            'username': current_user.username,
            'nickname': current_user.nickname,
            'email': current_user.email,
            'phone': current_user.phone,
            'avatar': current_user.avatar
        }
    }

@bp.route('/api/profile/update', methods=['POST'])
@login_required
def update_profile():
    nickname = request.form.get('nickname')
    email = request.form.get('email')
    phone = request.form.get('phone')
    
    # 处理头像上传
    avatar_url = None
    if 'avatar' in request.files:
        avatar = request.files['avatar']
        if avatar and avatar.filename:
            try:
                avatar_url = minio_util.upload_file(avatar.stream, avatar.filename)
            except Exception as e:
                return {'success': False, 'message': f'头像上传失败：{str(e)}'}
    
    success, message = auth_service.update_user_profile(
        current_user.id, 
        email=email, 
        phone=phone, 
        nickname=nickname,
        avatar=avatar_url
    )
    
    return {'success': success, 'message': message if not success else '个人信息更新成功'}

@bp.route('/api/change-password', methods=['POST'])
@login_required
def change_password():
    data = request.get_json()
    if not data:
        return {'success': False, 'message': '无效的请求数据'}
        
    current_password = data.get('current_password')
    new_password = data.get('new_password')
    
    if not current_password or not new_password:
        return {'success': False, 'message': '请填写所有必填字段'}
    
    success, message = auth_service.update_user_password(current_user.id, current_password, new_password)
    return {'success': success, 'message': message if not success else '密码修改成功'}